<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div class="hand">
      <form @submit.prevent>
        品牌名称:
        <input type="text" v-model.trim="brandname" @keyup.esc="brandname=''">
        <button type="submit" @click="addNewBrand">添加品牌</button>
      </form>
    </div>
    <div class="content">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>品牌名称</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in brands" :key="item.id">
            <td>{{index+1}}</td>
            <td>{{item.brandName}}</td>
            <td>{{item.status}}</td>
            <td>{{item.addTime | dateFormat}}</td>
            <td>
              <!-- <a :id="item.id" href="#" @click.prevent = 'removeBrand'>删除</a> -->
              <a href="#" @click.prevent = 'remove(item.id)'>删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <script src="./lib/vue.js"></script>
  <script>
    // 格式化时间 过滤器
    Vue.filter('dateFormat' , (dateStr)=>{
      const dt = new Date(dateStr)
      const y = dt.getFullYear()
      const m = zoneFormat(dt.getMonth() +1)
      const d = zoneFormat(dt.getDate())

      const hh = zoneFormat(dt.getHours())
      const mm = zoneFormat(dt.getMinutes())
      const ss = zoneFormat(dt.getSeconds())

      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    })
    function zoneFormat(n){
      return n > 9 ? n : '0' + n 
    }
    const vm = new Vue({
      el:'#app',
      data:{
        brands:[
          {id:1,brandName:'宝马',status:true,addTime:new Date()},
          {id:2,brandName:'奔驰',status:false,addTime:new Date()},
          {id:3,brandName:'奥迪',status:true,addTime:new Date()},
        ],
        brandname:'',
        nextId:4,
      },
      methods:{
        addNewBrand(){
          if(!this.brandname) return alert('品牌名不能为空')
          this.brands.push({
            id:this.nextId,
            brandName:this.brandname,
            status:true,
            addTime:new Date()
          })
          this.brandname = ''
          this.nextId ++
        },
        removeBrand(e){
          let id = e.target.id
          for(var i = 0;i<this.brands.length;i++){
            if(this.brands[i].id == id){
              this.brands.splice(i,1)
            }
          }
        },
        //根据id删除
        remove(id){
          this.brands = this.brands.filter(i=>i.id !== id)
        }
      }
    })
  </script>
</body>
</html>